<?php

class StdLibStandardFunctions implements CliLibrary
{
	private static $functions = array(
		'floor' => 'f_floor',
		'ceil' => 'f_ceil',
		'sin' => 'f_sin',
		'cos' => 'f_cos',
		'tan' => 'f_tan',
		'fsum' => 'f_fsum',
		'sqrt' => 'f_sqrt',
		'log' => 'f_log',
		'ln' => 'f_ln',
		'logn' => 'f_logn',
	);

	public static function addLibrary (CliMode $mode)
	{
		$mode->addFunctions(__CLASS__, self::$functions);
	}

	public static function f_floor (ArgContext $args)
	{
		$args->requireCount(1);
		return floor($args->toNumber(0));
	}

	public static function f_ceil (ArgContext $args)
	{
		$args->requireCount(1);
		return ceil($args->toNumber(0));
	}

	public static function f_sin (ArgContext $args)
	{
		$args->requireCount(1);
		$rad = self::getRadians($args->toNumber(0), $args);
		return sin($rad);
	}

	public static function f_cos (ArgContext $args)
	{
		$args->requireCount(1);
		$rad = self::getRadians($args->toNumber(0), $args);
		return cos($rad);
	}

	public static function f_tan (ArgContext $args)
	{
		$args->requireCount(1);
		$rad = self::getRadians($args->toNumber(0), $args);
		return tan($rad);
	}

	public static function f_fsum (ArgContext $args)
	{
		$args->requireTypes('variable', 'number', 'number', 'number');

		$lower = $args->toNumber(1);
		$upper = $args->toNumber(2);
		$sum = 0;

		for ($i = $lower; $i <= $upper; $i += 1)
		{
			$args[0]->set($i, $args->getContext());
			$sum += $args->toNumber(3);
		}

		return $sum;
	}

	public static function f_sqrt (ArgContext $args)
	{
		$args->requireCount(1);
		return sqrt($args->toNumber(0));
	}

	public static function f_log (ArgContext $args)
	{
		$args->requireCount(1);
		return log10($args->toNumber(0));
	}

	public static function f_ln (ArgContext $args)
	{
		$args->requireCount(1);
		return log($args->toNumber(0));
	}

	public static function f_logn (ArgContext $args)
	{
		$args->requireCount(2);
		return log($args->toNumber(0), $args->toNumber(1));
	}

	private static function getRadians ($value, ArgContext $args)
	{
		if ($args->getConf('degree') == 'deg')
		{
			return deg2rad($value);
		}

		return $value;
	}
}
?>